#region File Header
//----------------------------------------------------------------
// Copyright (C) 2002 Stefan Kyntchev
// All rights reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY 
// OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT 
// LIMITED TO THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR 
// FITNESS FOR A PARTICULAR PURPOSE.
//----------------------------------------------------------------
#endregion File Header

using System;
using System.IO;
using System.Collections;
using System.Collections.Specialized;
using System.Configuration;
using System.Web;
using AirWeb.Security;
using System.Web.Mail;
using AirWeb.Support.Diagnostics;

namespace AirWeb.ApplicationTools.Mail
{
	/// <summary>
	/// Mail helper is used to send a templetized e-mails to a set of recipients.
	/// The replacements are made for each recipient. The template is stored in
	/// the configuration settings
	/// </summary>
	public class MailHelper
	{
		private string m_originatorName;
		private string m_originatorEmail;
		private string m_EmailBodyTemplate;
		private string m_EmailSubjectTemplate;
		private string m_SmtpGateway;
		private HttpContext m_page;
		private ArrayList m_Recipients = new ArrayList();

		/// <summary>
		/// The body of the e-mail message
		/// </summary>
		public string TemplateBody
		{
			get
			{
				return m_EmailBodyTemplate;
			}
			set
			{
				m_EmailBodyTemplate = TokenReplace(value,null); 
			}
		}

		/// <summary>
		/// The subject of the message
		/// </summary>
		public string TemplateSubject
		{
			get
			{
				return m_EmailSubjectTemplate;
			}
			set
			{
				m_EmailSubjectTemplate = TokenReplace(value,null); 
			}
		}


		public MailHelper()
		{
			LoadConfig();
		}

		/// <summary>
		/// Constructs a new mail helper
		/// </summary>
		/// <param name="i_mailType">the name of the template. All templates are stored as text files in 
		/// config directory</param>
		/// <param name="i_page"></param>
		public MailHelper(string i_mailType, HttpContext i_page)
		{
			m_page = i_page;

			LoadConfig();

			NameValueCollection config = (NameValueCollection)
				ConfigurationSettings.GetConfig("flashBack/emailPreferences");	

			// Load the body of the mail template
			string filename = config[i_mailType];

			if(filename == null)
				throw new ArgumentException("The supplied e-mail template " + i_mailType + " is not a valid e-mail template");

			string path = m_page.Request.PhysicalApplicationPath + "config\\" + filename;

			try
			{
				StreamReader r = File.OpenText(path);
				m_EmailBodyTemplate = r.ReadToEnd();
				r.Close();
			}
			catch(Exception ex)
			{
				m_EmailBodyTemplate = ex.Message;
			}

			m_EmailSubjectTemplate = "";
			m_EmailBodyTemplate = TokenReplace(m_EmailBodyTemplate,null); 
		}

		/// <summary>
		/// Loads the configuration settings 
		/// </summary>
		void LoadConfig()
		{
			NameValueCollection config = (NameValueCollection)
				ConfigurationSettings.GetConfig("flashBack/emailPreferences");			

			m_originatorName =  config["originatorName"];
			m_originatorEmail =  config["originatorEmail"];
			m_SmtpGateway =  config["smtpGateway"];
		}

		/// <summary>
		/// Adds a user as a recipient for the e-mail message
		/// </summary>
		/// <param name="u">User to recive the message</param>
		public void AddRecipient(User u)
		{
			m_Recipients.Add(u);
		}

		/// <summary>
		/// Replaces well-known tokens with information taken from the supplied user
		/// </summary>
		/// <param name="i_text">Text to be token replaced </param>
		/// <param name="i_user">the User, whos information will be used</param>
		/// <returns></returns>
		protected string TokenReplace(string i_text, User i_user)
		{
			if(i_user != null)
			{
				i_text = i_text.Replace("[USER_NAME]",i_user.Name);
				i_text = i_text.Replace("[USER_PASSWORD]",i_user.Password);
			}

			i_text = i_text.Replace("[ORIGINATOR_NAME]",m_originatorName);
			i_text = i_text.Replace("[ORIGINATOR_EMAIL]",m_originatorEmail);

			string url = m_page.Request.Url.Scheme + "://" + m_page.Request.Url.Authority;

			i_text = i_text.Replace("[SITE_URL]",url);
			return i_text;
		}

		/// <summary>
		/// This method generetes the customized e-mails for each user and sends them
		/// </summary>
		public void SendMail(object i_state)
		{
			try
			{
				foreach(User u in m_Recipients)
				{
					string subject = TokenReplace( m_EmailSubjectTemplate, u);
					string body = TokenReplace( m_EmailBodyTemplate, u);
			
					SmtpMail.SmtpServer = m_SmtpGateway;

					MailMessage m = new MailMessage();

					m.From = m_originatorEmail;
					m.To = u.Email;
					m.Body = body;
					m.Subject = subject;
					SmtpMail.Send(m);
					ApplicationLog.WriteTrace("E-mail was sent to: " + u.Email);
				}
			}
			catch(Exception e)
			{
				ApplicationLog.FormatException(e,"Exception occured while sending E-mail messages!");
			}
		}

		/// <summary>
		/// Sends e-mail from known originator to a specific user. THe originator is
		/// retrieved vrom the config settings
		/// </summary>
		/// <param name="i_recipient">e-mail address of the recipient</param>
		/// <param name="i_subject">subject of the e-mail</param>
		/// <param name="i_body">body of the e-mail</param>
		public void SendMail(string i_recipient, string i_subject, string i_body)
		{
			try
			{
				SmtpMail.SmtpServer = m_SmtpGateway;

				MailMessage m = new MailMessage();

				m.From = m_originatorEmail;
				m.To = i_recipient;
				m.Body = i_body;
				m.Subject = i_subject;
				SmtpMail.Send(m);
			}
			catch	{}
		}
	}
}
